%%%-------------------------------------------------------------------
%%% @author Rain
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 06. 7月 2022 11:02
%%%-------------------------------------------------------------------
-module(gate_util).
-author("Rain").

%% API
-export([send_msg/2, send_msg/3, send_sock_msg/2, get_process_sock/0, set_process_sock/1]).

get_process_sock() ->
    get(socket).

set_process_sock(Sock) ->
    put(socket, Sock).

%% @doc obj_svr中调用
send_msg(MsgId, Msg) ->
    UidValue = obj_svr:get_uid_value(),
    send_msg(MsgId, Msg, UidValue).

send_msg(MsgId, Msg, UidValue) ->
    case uid_svr:get_uid_route_pid(UidValue) of
        Pid when is_pid(Pid) ->
            Pid ! {to_client_msg, MsgId, Msg};
        _ ->
            pass
    end.


%% @doc gate_route_svr调用
send_sock_msg(MsgId, Msg) ->
    case get_process_sock() of
        Sock when is_port(Sock) ->
            case is_binary(Msg) of
                true ->
                    BinMsg = Msg;
                _ ->
                    BinMsg = msg_proto:pack_msg(MsgId, Msg)
            end,
            io:format("~p [SEND_MSG] USER(~p) MsgId ~p Msg ~p ~n",[self(), get(uid_value), MsgId, Msg]),
            try
                erlang:port_command(Sock, BinMsg, [force, nosuspend])
            catch
                Err:Reason:Stack  ->
                    io:format("~p [SEND_MSG_ERR] ERR ~p REASON ~p STACK ~p ~n",[self(), Err, Reason, Stack])
            end;
        _ ->
            pass
    end.